package com.spooky.sync.net;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;

public class Connector {
	private Socket mSocket;
	private BufferedWriter mBufferedWriter;
	private BufferedReader mBufferedReader;
	/** DATA **/
	private String mHost;
	private Integer mPort;

	public Connector() {
		mSocket = null;
		mBufferedWriter = null;
		mBufferedReader = null;
		mHost = null;
		mPort = null;
	}

	public Connector(String host, int port) {
		mHost = host;
		mPort = port;
	}

	public void connect() throws IOException {
		connect(mHost, mPort);
	}

	public void connect(String host, int port) throws IOException {
		mHost = host;
		mPort = port;
		mSocket = new Socket(mHost, mPort);
		mBufferedWriter = new BufferedWriter(new OutputStreamWriter(mSocket.getOutputStream(), "UTF-8"));
		mBufferedReader = new BufferedReader(new InputStreamReader(mSocket.getInputStream(), "UTF-8"));
	}

	public void disconnect() throws IOException {
		mBufferedWriter.close();
		mBufferedReader.close();
		mSocket.close();
	}

	public boolean isOpen() {
		return mSocket != null && mSocket.isConnected() && !mSocket.isClosed();
	}

	public BufferedWriter getBufferedWriter() {
		return mBufferedWriter;
	}

	public BufferedReader getBufferedReader() {
		return mBufferedReader;
	}
}
